package com.qy.common.broadcastReceiver;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.qy.common.utils.Tip;

/**
 * https://blog.csdn.net/weixin_34185512/article/details/85859476
 * android 蓝牙设备监听广播
 */
public class BlueToothReceiver extends BroadcastReceiver {

    private String btMessage = "";
    //监听蓝牙状态

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
        //连接
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            btMessage = device.getName();//蓝牙的名字
            //已经连接，开始你的操作，我是用了播放音乐的方式提醒客户
            Tip.show(btMessage + "已经连接，开始你的操作");
            Log.d("aaa", btMessage + "已经连接，开始你的操作");

        } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            Log.e("断开", "onReceive: " + device.getName());//蓝牙的名字
            btMessage = device.getName() + "蓝牙连接已断开！！";
            Tip.show(btMessage);
            Log.d("aaa", btMessage);
            //已经断开，开始你的操作，我是用了播放音乐的方式提醒客户，然后在activity里写了一个方法，继续连接。

        }

        if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
            int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
                    BluetoothAdapter.ERROR);
            switch (state) {
                case BluetoothAdapter.STATE_OFF:
                    Log.d("aaa", "STATE_OFF 手机蓝牙关闭");
                    break;
                case BluetoothAdapter.STATE_TURNING_OFF:
                    Log.d("aaa", "STATE_TURNING_OFF 手机蓝牙正在关闭");
                    break;
                case BluetoothAdapter.STATE_ON:
                    Log.d("aaa", "STATE_ON 手机蓝牙开启");
                    break;
                case BluetoothAdapter.STATE_TURNING_ON:
                    Log.d("aaa", "STATE_TURNING_ON 手机蓝牙正在开启");
                    break;
            }
        }
    }

}